package com.audaque.springboot.foshanupload.web.util;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;

/**
 * @author zgb
 * @desc ...
 * @date 2022-01-26 16:50:15
 */
@Slf4j
public class ReqParamUniqueUtils {


    /**
     * @param reqParamJSON     请求的参数，这里通常是JSON
     * @param excludeKeys 请求参数里面要去除哪些字段再求摘要
     * @return 去除参数的MD5摘要
     */
    public static String dedupParamMD5(final String reqParamJSON, String... excludeKeys) {
        String decreptParam = reqParamJSON;

        TreeMap paramTreeMap = JSONUtil.toBean(decreptParam, TreeMap.class);
        if (excludeKeys != null) {
            List<String> dedupExcludeKeys = Arrays.asList(excludeKeys);
            if (!dedupExcludeKeys.isEmpty()) {
                for (String dedupExcludeKey : dedupExcludeKeys) {
                    paramTreeMap.remove(dedupExcludeKey);
                }
            }
        }

        String paramTreeMapJSON = JSONUtil.toJsonStr(paramTreeMap);
        String md5deDupParam = jdkMD5(paramTreeMapJSON);
        log.debug("md5deDupParam = {}, excludeKeys = {} {}", md5deDupParam, Arrays.deepToString(excludeKeys), paramTreeMapJSON);
        return md5deDupParam;
    }

    @SneakyThrows
    private static String jdkMD5(String src) {
        String res = null;
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] mdBytes = messageDigest.digest(src.getBytes());
        res = DatatypeConverter.printHexBinary(mdBytes);
        return res;
    }

}
